const Router = require('koa-router');
const db = require('../database/config/db');
const COMMENTS = 'comments';
const USERS = 'user';
const GOODS = 'goods';

const router = new Router();

// 根据商品ID读取评论列表
router.get('/getCommentsListByGoodsId', async ctx => {
    try {
        // 商品ID 当前请求的页数
        let {goodsId, page} = ctx.request.query;
        let num = 10; // 每页显示数量
        let start = (page - 1) * num; // 开始位置
        // 顶级评论查询
        let sql = `SELECT comments.*, username, avatar FROM comments LEFT JOIN user ON comments.uid = user.id WHERE comments.goodsId = '${goodsId}' AND pid=0 ORDER BY ctime DESC LIMIT ${start}, ${num}`;
        console.log(sql);
        let result = await db.QUERY_All(sql);
        // 循环每个顶级评论，查找二级评论
        for (const top of result) {
            // let subComments = await db.QUERY_All(`SELECT comments.*, username, avatar FROM comments LEFT JOIN user ON comments.uid = user.id WHERE comments.goodsId = '${goodsId}' AND pid = ${top.cid} ORDER BY ctime ASC`);
            let subComments = await db.QUERY_All(`
                SELECT 
                    a.*, 
                    user.username AS reviewer_username, 
                    user.avatar AS reviewer_avatar
                FROM
                    (SELECT comments.*, username, avatar FROM comments LEFT JOIN user ON comments.uid = user.id WHERE comments.goodsId = '${goodsId}' AND pid = ${top.cid} ORDER BY ctime ASC)
                    AS a
                LEFT JOIN user ON a.reviewerId = user.id`);
            if (subComments.length > 0) {
                top.reply = subComments;
            }
        }
        // console.log(result);
        ctx.body = {
            code: 200,
            message: "请求成功",
            data: result
        }
    } catch (err) {
        ctx.body = {
            code: 500,
            message: err
        }
    }
})

// 给商品添加评论
router.post('/addComment', async ctx => {
    try {
        // 商品ID 当前请求的页数
        let {content, pid, replyId, uid, reviewerId, goodsId} = ctx.request.body;
        console.log(content, pid, replyId, uid, reviewerId, goodsId);
        let result = await db.INSERT_DATA(COMMENTS, {
            content, pid, replyId, uid, reviewerId, goodsId
        });
        ctx.body = {
            code: 200,
            message: "评论成功",
            data: result,
        }
    } catch (err) {
        ctx.body = {
            code: 500,
            message: err
        }
    }
});

// ====================


module.exports = router;